package com.crm.sys.handler;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.crm.im.core.constant.IMConstant;
import com.crm.im.core.handler.IMRequestHandler;
import com.crm.im.core.model.Message;
import com.crm.im.core.model.ReplyBody;
import com.crm.im.core.model.SentBody;
import com.crm.im.core.session.IMSession;
import com.crm.sys.model.SysMessage;
import com.crm.sys.service.SysService;
import com.crm.util.StringUtil;
/**
 * 推送离线消息
 */
@Service("offlineMessageHandler")
public class PushOfflineMessageHandler implements IMRequestHandler {
	@Autowired
	private SysService sysService;
	
	protected final Logger logger = Logger
			.getLogger(PushOfflineMessageHandler.class);

	public ReplyBody process(IMSession ios, SentBody message) {

		ReplyBody reply = new ReplyBody();
		reply.setCode(IMConstant.ReturnCode.CODE_200); 
		try {
			String account = message.get("account");
			SysMessage ms = new SysMessage();
			ms.setReceiveuser(Long.parseLong(account));  
			ms.setType(0);
			List<SysMessage>  messageList = sysService.getMessageList(ms);
			if(messageList!=null&&messageList.size()>0){
				//获取到存储的离线消息发送
				for(SysMessage msg:messageList){
					Message  m = new Message();
					m.setMid(StringUtil.getUUID());
					if(msg.getSenduser()==0L){
						m.setSender("system");
						m.setType("2");
					}else{
						m.setSender(String.valueOf(msg.getSenduser())+"|"+msg.getSendusername());	
						m.setType("1");
					}
					m.setSenderName(msg.getSendusername());
					m.setReceiver(String.valueOf(msg.getReceiveuser()));
					m.setContent(msg.getContent());
					ios.write(m);
				}
				sysService.updateMessageState(ms);
			}
			
			 
 
		} catch (Exception e) {
			reply.setCode(IMConstant.ReturnCode.CODE_500);
			e.printStackTrace();
			logger.error("拉取离线消息失败", e);
		}
		return reply;
	}
}